//
//  RecommendViewController.swift
//  swiftDemo
//
//  Created by Gerry on 2021/11/17.
//

import UIKit
import FSPagerView

private let cellIdentifier = "cellIdentifier"
private let headerViewIdentifier = "RecommendHeaderView"
private let kFSPagerViewCell = "FSPagerViewCell"

private let kFSPagerViewHeight : CGFloat = 130.0
private let kRecommendScrollViewHeight : CGFloat = 90.0


class RecommendViewController: UIViewController {

    private var viewModel : RecommendViewModel = RecommendViewModel()
    
    private lazy var collectionView : UICollectionView = { [unowned self] in
//        let itemW : CGFloat = (kScreenW - 10*3)/2.0
//        let itemH : CGFloat = itemW * 3 / 4
        
        let layout = ZLCollectionViewVerticalLayout()
        layout.delegate = self
        
        let collectionView = UICollectionView.init(frame: self.view.bounds, collectionViewLayout: layout)
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.backgroundColor = UIColor.init(r: 240, g: 240, b: 240)
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellIdentifier)
        collectionView.register(Style1Cell.self, forCellWithReuseIdentifier: "Style1Cell")
        collectionView.register(Style2Cell.self, forCellWithReuseIdentifier: "Style2Cell")
        collectionView.register(RecommendHeaderView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier:headerViewIdentifier)
        collectionView.contentInset = UIEdgeInsets.init(top: kFSPagerViewHeight+kRecommendScrollViewHeight, left: 0, bottom: 0, right: 0)
        
        // 根据父控件大小自动缩放
//        collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight]

        return collectionView
    }()
    
    // FSPagerView不支持自动布局
    private lazy var pagerView :  FSPagerView = {
        let frame = CGRect.init(x: 0, y: -kFSPagerViewHeight-kRecommendScrollViewHeight, width: kScreenW, height: kFSPagerViewHeight)
        let pagerView = FSPagerView.init(frame: frame)
        pagerView.dataSource = self
        pagerView.delegate = self
        pagerView.isInfinite = true
        pagerView.automaticSlidingInterval = 3;
        pagerView.register(FSPagerViewCell.self, forCellWithReuseIdentifier:kFSPagerViewCell)
        return pagerView
    }()
    
    private lazy var pageControl : FSPageControl = {
        let maxWidth = kScreenW - 100
        let pageControl = FSPageControl(frame: CGRect.init(x: 100, y: kFSPagerViewHeight-15, width: maxWidth, height: 8))
        pageControl.contentHorizontalAlignment = .right
        pageControl.contentInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
        pageControl.setPath(UIBezierPath(rect: CGRect(x: 0, y: 0, width: 8, height: 8)), for: .normal)
        pageControl.setPath(UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: 8, height: 8)), for: .selected)
        return pageControl
    } ()
    
    
    private lazy var recommendView : RecommendScrollView = {
        let recommendView = RecommendScrollView()
        recommendView.backgroundColor = .white
        return recommendView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        setupUI()
        
        viewModel.requestBanner { isSuccess, result in
            self.pageControl.currentPage = 0
            self.pageControl.numberOfPages = self.viewModel.bannerImages.count;
            self.pagerView.reloadData()
        }
        
        viewModel.requestData { success, errMessage in
            if (!success) {
                print(errMessage ?? "Error")
                return;
            }
            self.collectionView.reloadData()
            self.recommendView.hotCates = self.viewModel.hotCates
        }
    }
}

extension RecommendViewController : FSPagerViewDataSource, FSPagerViewDelegate {
    public func numberOfItems(in pagerView: FSPagerView) -> Int {
        return self.viewModel.bannerImages.count;
    }
        
    public func pagerView(_ pagerView: FSPagerView, cellForItemAt index: Int) -> FSPagerViewCell {
        let cell = pagerView.dequeueReusableCell(withReuseIdentifier:kFSPagerViewCell, at: index)
        let bannerModel = self.viewModel.bannerImages[index]
        cell.imageView?.sd_setImage(with: URL.init(string: bannerModel.pic_url ?? ""), completed: nil)
        cell.imageView?.contentMode = .scaleAspectFill
        cell.textLabel?.text = bannerModel.title
        return cell
    }
    
    func pagerView(_ pagerView: FSPagerView, didSelectItemAt index: Int) {
        print("didSelectItemAt \(index)")
    }
    
    func pagerViewDidScroll(_ pagerView: FSPagerView) {
        pageControl.currentPage = pagerView.currentIndex
    }
    
    func pagerViewWillEndDragging(_ pagerView: FSPagerView, targetIndex: Int) {
        pageControl.currentPage = targetIndex
    }
}

extension RecommendViewController : ZLCollectionViewBaseFlowLayoutDelegate {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets.init(top: 10, left: 10, bottom: 10, right: 10)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
            return 10
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 10
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize.init(width: kScreenW, height: 40)
    }
}

extension RecommendViewController {
    func setupUI() {
        view.addSubview(collectionView)
        collectionView.addSubview(pagerView)
        collectionView.snp.makeConstraints { make in
            make.edges.equalTo(0)
        }
        pagerView.addSubview(pageControl)
        collectionView.addSubview(recommendView)
        
        recommendView.snp.makeConstraints { make in
            make.left.equalTo(0)
            make.top.equalTo(pagerView.snp.bottom)
            make.width.equalTo(collectionView)
            make.height.equalTo(kRecommendScrollViewHeight)
        }
    }
}

extension RecommendViewController : UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let m = viewModel.hotCates[section]
        return m.room_list!.count
    }

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return viewModel.hotCates.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Style1Cell", for: indexPath) as! Style1Cell
        let m = viewModel.hotCates[indexPath.section]
        let roomItem = m.room_list![indexPath.row]
        cell.itemModel = roomItem
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerViewIdentifier, for: indexPath)
        guard let hv = headerView as? RecommendHeaderView else {
            return headerView
        }
        hv.titleLabel.text = viewModel.hotCates[indexPath.section].tag_name
        return headerView
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let itemW : CGFloat = (kScreenW - 10*3)/2.0
//        let itemH : CGFloat = itemW * 3 / 4

        let sz = collectionView.ar_sizeForCell(withIdentifier:"Style1Cell",
                                               indexPath: indexPath,
                                               fixedWidth: itemW) { cell in
            let cell = cell as! Style1Cell
            let m = self.viewModel.hotCates[indexPath.section]
            let roomItem = m.room_list![indexPath.row]
            cell.itemModel = roomItem
        }

        return sz
    }
}

extension RecommendViewController {
    
}
